package com.bincloud.vue.admin.web.config;

import com.bincloud.vue.admin.common.exception.BaseException;
import com.bincloud.vue.admin.common.exception.CodeMsg;
import com.bincloud.vue.admin.common.model.dto.response.BaseResDTO;
import com.bincloud.vue.admin.common.util.ResponseUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;

/**
 * @Description: 全局异常捕获
 * @Author: bincloud, mvpzhou
 * @Date: Create By bincloud, mvpzhou on 2022/2/26
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public BaseResDTO<String> exceptionHandler(Exception e) {
        return ResponseUtils.fail(e.getMessage());
    }

    @ExceptionHandler(BaseException.class)
    public BaseResDTO<String> exceptionHandler(BaseException e) {
        return ResponseUtils.fail(e.getMessage());
    }

    @ExceptionHandler(BindException.class)
    public BaseResDTO<String> exceptionHandler(BindException e) {
        List<FieldError> fieldErrors = e.getFieldErrors();
        StringBuilder errMsg = new StringBuilder();
        fieldErrors.forEach(err-> errMsg.append(err.getDefaultMessage()).append(";"));
        errMsg.deleteCharAt(errMsg.length() - 1);
        return ResponseUtils.fail(CodeMsg.VALIDATE_ERROR.getCode(), errMsg.toString());
    }
}
